package com.smgeek.gkrpc.common.utils;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

public class ReflectionUtils {

    /**
     * 根据class创建对象
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T newInstance(Class<T> clazz){
        try {
            return clazz.newInstance();
        }catch (Exception e){
            throw new IllegalStateException(e);
        }
    }


    public static  Method[] getPublicMethods(Class clazz){
        Method[] declaredMethods = clazz.getDeclaredMethods();
        List<Method> list = new ArrayList<>();

        for(Method method: declaredMethods){
            if(Modifier.isPublic(method.getModifiers())){
                list.add(method);
            }
        }

        return list.toArray(new Method[0]);
    }

    /**
     *
     * 调用指定对象的方法
     * @param obj
     * @param method
     * @param args
     * @return
     */
    public static Object invoke(Object obj,Method method,Object... args){
        try {
            return method.invoke(obj,args);
        }catch ( Exception e){
            throw new IllegalStateException(e);
        }
    }

}
